package com.hse.virtualnetwork;

import com.hse.network.IEndDevice;
import com.hse.network.Network;
import com.hse.network.exceptions.NetworkException;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.util.Arrays;

/**
 * Created by IntelliJ IDEA.
 * User: Lexa
 * Date: May 31, 2009
 * Time: 6:42:25 PM
 * To change this template use File | Settings | File Templates.
 */
public class VirtualEndDevice implements IEndDevice {
    private final static Short PORT_NUMBER = 8789;
    private final Socket sock;

    public VirtualEndDevice() {
        sock = new Socket();
    }

    public void connect(Short panId) throws NetworkException {
        try {
            sock.connect(new InetSocketAddress("127.0.0.1", PORT_NUMBER));
        } catch (IOException e) {
            throw new NetworkException(e);
        }
    }

    public Network[] scan() throws NetworkException {
        final Network[] networks = new Network[1];
        networks[0] = new Network(PORT_NUMBER);
        return networks;
    }

    public byte[] recv() throws NetworkException {
        try {
            byte[] data = new byte[1024];
            int recvSize = sock.getInputStream().read(data);
            return Arrays.copyOf(data, recvSize);
        } catch (IOException e) {
            throw new NetworkException(e);
        }
    }

    public void send(byte[] data) throws NetworkException {
        try {
            sock.getOutputStream().write(data);
        } catch (IOException e) {
            throw new NetworkException(e);
        }
    }

    public boolean canRead() {
        try {
            return sock.getInputStream().available() > 0;
        } catch (IOException e) {
            return false;
        }
    }

    public void close() {
        try {
            sock.close();
        } catch (IOException e) {
        }
    }
}
